
export let istest = true; // 是否是正式
export let baseURL = istest?"https://www.ataattila.com":"http://ata.henantelida.com"; //线上域名

export function toast(title, mask = false, duration = 3000){
	uni.showToast({
		title: title,
		mask:mask,
		icon: 'none',
		duration: duration
	})
}

export function go(index, url) {
	if (index == 1) { // 返回上级页面
		// #ifdef H5
		// 解决 H5页面刷新后 无法返回上个页面
		let canNavBack = getCurrentPages()
		if (canNavBack && canNavBack.length > 1) {
			uni.navigateBack({
				delta: url,
				animationType: 'pop-out',
				animationDuration: 300
			});
		} else {
			history.back();
		}
		// #endif
		// #ifdef APP-PLUS
		uni.navigateBack({
			delta: url,
			animationType: 'pop-out',
			animationDuration: 300
		});
		// #endif
	} else if (index == 2) { // 页面跳转
		uni.navigateTo({
			url: url,
			animationType: 'pop-in',
			animationDuration: 300
		})
	} else if (index == 3) { // 跳转tab页面
		uni.switchTab({
			url: url,
			animationType: 'pop-in',
			animationDuration: 300
		})
	} else if (index == 4) { // 关闭所有页面跳转
		uni.reLaunch({
			url: url,
			animationType: 'pop-in',
			animationDuration: 300
		})
	} else if (index == 5) {
		uni.redirectTo({ // 关闭当前页面，跳转到某个页面
			url: url,
		});
	}
}

//common.js
/**
 * @description: 图片转base64
 * @param {String} url 需要转换的图片原链接（http://....jpg）
 * @param {String} outputFormat 转换出来的图片的类型（canvas支持jpg/png格式）
 * @return: 返回图片对应的base64编码
 */
export function getBas64(url, outputFormat = "image/jpg") {
	return new Promise(function(resolve, reject) {
		let canvas = document.createElement("canvas");
		let ctx = canvas.getContext("2d");
		let img = new Image();
		img.crossOrigin = "";

		img.addEventListener("load", () => {
			canvas.height = img.height;
			canvas.width = img.width;
			ctx.drawImage(img, 0, 0);
			let dataURL = canvas.toDataURL(outputFormat);
			canvas = null;
			resolve(dataURL);
		});
		img.addEventListener("error", err => reject(err));
		img.src = url;
	});
};


/**
 * 将base64转换为file
 */
export function dataURLtoFile(dataurl, filename) { //将base64转换为文件
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], filename, {
		type: mime
	});
}


/**
 * 将base64转换为Blob
 */
export function dataURLtoBlob(urlData, fileType) {
	let bytes = window.atob(urlData);
	let n = bytes.length;
	let u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bytes.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: fileType
	});
}


/**
 * 复制粘贴版
 */
export function copy(code,text) {
	uni.setClipboardData({
		data: code+'',
		success: function() {
			uni.showToast({
				icon: 'none',
				title: text
			});
		}
	});
}


/**
 * 图片处理-选择图片
 */
export function chooseImage(count = 1) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: count, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			success: res => {
				resolve(res);
			}
		});
	}).catch(e => {
		reject(e)
	})
}


/**
 * 图片处理-上传图片
 */
export function uploadImage(api, url) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseURL + api,
			filePath: url,
			name: 'file',
			// header: {
			// 	'Authori-zation': 'Bearer ' + uni.getStorageSync('access_token') || '',
			// },
			formData: {
				'access_token': uni.getStorageSync('access_token') || '',
			},
			success: res => {
				
				res = JSON.parse(res.data);
				if (res.status === 200) {
					resolve(res)
				} else {
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '上传失败',
					});
				}
			}
		});
	}).catch(e => {
		reject(e)
	})
}


/**
 * 图片处理-预览图片
 */
export function previewImage(urls = [], current = 0) {
	uni.previewImage({
		urls: urls,
		current: current,
		indicator: 'default',
		loop: true,
		fail(err) {
			console.log('previewImage出错', err)
		},
	})
}


/**
 * 下载
 */
export function downloadFile(downUrl) {
	console.log(downUrl)
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: downUrl, //图片下载地址
			success: res => {
				if (res.statusCode === 200) {
					resolve(res)
				}
			}
		});
	}).catch(e => {
		reject(e)
	})
}


/**
 * 保存图片到系统相册
 */
export function saveImageToPhotosAlbum(url) {
	uni.saveImageToPhotosAlbum({
		filePath: url,
		success: function() {
			uni.showToast({
				title: '图片保存成功',
				icon: 'none',
			});
		},
		fail: function(e) {
			uni.showToast({
				title: '图片保存失败',
				icon: 'none',
			});
		}
	});
}


/**
 * 微信、支付宝，支付
 * payType：支付类型
 * orderInfo：订单数据
 * payType == wxpay，则orderInfo是对象，支付宝orderInfo为字符串
 */
export function requestPayment(payType, orderInfo) {
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			provider: payType, //支付类型
			orderInfo: orderInfo, //微信、支付宝，订单数据
			success: function(res) {
				resolve(res)
			},
			fail: function(err) {
				resolve(err)
			}
		});
	}).catch(e => {
		reject(e)
	})
}

/**
 * 舍去指定小数位（不进行四舍五入）
 */
export function toFixed(num, decimal) {
	num = num.toString();
	let index = num.indexOf('.');
	if (index !== -1) {
		num = num.substring(0, decimal + index + 1)
	} else {
		num = num.substring(0)
	}
	return parseFloat(num).toFixed(decimal)
}


// 节流
var noClick = true,
	noClickTimes = 500
export function repeat(methods, info) {
	if (noClick) {
		noClick = false;
		if ((info && info !== '') || info == 0) {
			methods(info);
		} else {
			methods();
		}
		setTimeout(() => {
			noClick = true;
		}, noClickTimes)
	} else {
		uni.showToast({
			title: '操作频繁，请稍后再试',
			icon: "none"
		})
	}
}

import { BigNumber } from 'bignumber.js';
// +
export function plus(a, b) {
  a = BigNumber(a);
  b = BigNumber(b);
  return a.plus(b).toNumber();   //结果需要用toNumber转为普通数字
}
// -
export function minus(a, b) {
  a = BigNumber(a);
  b = BigNumber(b);
  return a.minus(b).toNumber();
}
// *
export function times(a, b) {
  a = BigNumber(a);
  b = BigNumber(b);
  return a.times(b).toNumber();
}
// /
export function div(a, b) {
  a = BigNumber(a);
  b = BigNumber(b);
  return a.div(b).toNumber();
}
/**
 * this.$plus(1,2) // 加
 * this.$minus(1,2) // 减
 * this.$times(1,2) // 乘
 * this.$div(1,2) // 除
 * 相等：max.eq(min)
 * 小于：max.lt(min)
 * 小于等于：max.lte(min)
 * 大于：max.gt(min)
 * 大于等于：max.gte(min)
 * 是否是0：max.isZero()
 * 精度调整：dp(4) // 55.833333333333336 == 55.8333
 * let a = BigNumber(20.123456)
 * a.toNumber()
 * a.toString()
 * a.dp(4).toNumber()
 * 
 */